/*
 * @Author: Crism
 * @Date: 2018-08-03 13:43:28
 * @LastEditors: Crism
 * @LastEditTime: 2018-08-03 15:53:42
 * @Description: 
 * @Email: crism@qq.com
 *
 *      options {
 *          bucket          :    // 七牛空间名
 *          filePath        :    // 文件路径
 *          access_key      :    // 七牛的accessKey
 *          secret_key      :    // 七牛的secretKey
 *          key   :    // 上传到服务器上的文件名
 *      }
 */


const qiniu = require("qiniu");
const IMAGEURL = 'http://p24hjnsdi.bkt.clouddn.com/';

const accessKey = '-wB7gbMbeR_0yOZ_Pige0M_YtUHPTBsggN6fj6lB';
const secretKey = 'aH0SbX_tdjKK9HJikgaIOATHanbe1-e2taIc7Aih';
const bucket = 'crism';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

module.exports.uploadImg = uploadImg;


async function uploadImg(filePath) {
    if(filePath == undefined) {
        return false;
    }
    /* 得到本地路径 */
    filePath = './authorportrait/' + filePath.slice(filePath.lastIndexOf('/') + 1);
    
    // if (!options.bucket && !options.key && !options.filePath) {
    //     console.log('请补全参数!');
    //     return false;
    // }

    // //默认参数
    // options = Object.assign({
    //     bucket: '',
    //     filePath: '',
    //     key: ''

    // }, options);



    //生成一个上传的凭证
    let options = {
        scope: bucket,
        expires: 7200,
        // callbackUrl: 'http://api.example.com/qiniu/upload/callback',
        // callbackBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
        // callbackBodyType: 'application/json'    
    }

    //设置七牛的上传空间
    const putPolicy = new qiniu.rs.PutPolicy(options);

    // 生成上传的Token
    const uploadToken = putPolicy.uploadToken(mac);

    // 实例化config
    const config = new qiniu.conf.Config();

    // 空间对应的机房
    config.zone = qiniu.zone.Zone_z2;

    let localFile = filePath;
    let key = filePath.slice(filePath.lastIndexOf('/')+ 1);
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();

    // 文件上传
    return new Promise((resolved, reject) => {
        formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr, respBody, respInfo) {
            if (respErr) {
                console.log("上传失败！");
                reject(respErr);
            }
            if (respInfo.statusCode == 200) {
                // console.log(IMAGEURL + respBody['key']);
                console.log("上传成功！");
                resolved(respBody);
            } else {
                console.log("上传错误！");
                resolved(respBody);
            }
        })
    })

}
